/** @format */

import { assign, isEmpty, merge } from 'lodash'
import { set, get } from 'mpath'
import { signFigures } from './rand'

/**
 *  updateUser projection 格式化
 *
 * @format
 * @param {object} projection
 * @return {*}
 * @memberof UserService
 */
export function formatUpdateUserProjection(projection: IUpdateQuery): IUpdateQuery {
  projection['$set'] = projection['$set'] || {}
  projection['$set'].updateTime = Date.now()
  // $push不存在属性  删除$push
  if (projection['$push'] && !Object.keys(projection['$push']).length) {
    delete projection['$push']
  }
  if (projection['$inc'] && !Object.keys(projection['$inc']).length) {
    delete projection['$inc']
  }
  console.log(projection)
  return projection
}

// 用户昵称脱敏
export function formatUserNick(name: string, replaceStr = '***') {
  let newStr: string
  if (name.length === 2) {
    newStr = name.substr(0, 1) + replaceStr + name.substr(-1, 1)
  } else if (name.length > 2) {
    let char = replaceStr
    newStr = name.substr(0, 1) + char + name.substr(-1, 1)
  } else {
    newStr = name + replaceStr
  }
  return newStr
}

/**
 *  不通过数据库select的情况下 获取更新后的数据
 *
 * @export
 * @param {IUserInfo} userInfo
 * @param {IDecoratorUpdateQuery} projection
 */
export function formatUpdatedDataByProjection(dbData: any, projection: IPreUpdateQuery) {
  let updatedDbData = assign({}, dbData)

  if (!isEmpty(projection.$set)) {
    Object.keys(projection.$set).forEach(key => {
      set(key, projection.$set?.[key], updatedDbData)
    })
  }

  if (!isEmpty(projection.$inc)) {
    Object.keys(projection.$inc).forEach(key => {
      const originValue = get(key, updatedDbData) || 0
      set(key, projection.$inc?.[key] + originValue, updatedDbData)
    })
  }

  if (!isEmpty(projection.$push)) {
    Object.keys(projection.$push).forEach(key => {
      const originValue = get(key, updatedDbData) || []
      if(originValue.length) set(key, [originValue, projection.$push?.[key]], updatedDbData)
      else set(key, [projection.$push?.[key]], updatedDbData)
    })
  }
  return updatedDbData
}

// 概率奖品配置 properiodfrom  properiodto
export function formatPrizeProbalityRange(prizes: IActivityPrize[]) {
  let originPeriod = 1
  return prizes.map(v => {
    if (!v.probability || v.properiodfrom) return v
    // 概率为0 跳出10000之外的区间
    if (+v.probability === 0)
      return {
        ...v,
        properiodfrom: 1000000,
        properiodto: 1000000
      }
    const properiodfrom = originPeriod
    const properiodto = +originPeriod + signFigures(+v.probability * 100) - 1
    originPeriod = +originPeriod + signFigures(+v.probability * 100)
    return {
      ...v,
      properiodfrom,
      properiodto
    }
  })
}
